define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'baidueditor'], function($, undefined, Backend, Table, Form, UE) {



    var Controller = {

        index: function() {

            // 初始化表格参数配置

            Table.api.init({

                extend: {

                    index_url: 'expenses/index',

                    add_url: 'expenses/index/add' + location.search,

                    edit_url: 'expenses/index/edit',

                    del_url: 'expenses/index/del',

                    table: 'expenses',

                    //设置不同操作下的弹窗宽高

                    area: {

                        add: ['800px', '450px'],

                        edit: ['800px', '450px']

                    }

                }

            });



            var table = $("#table");

            // 初始化表格

            table.bootstrapTable({

                url: $.fn.bootstrapTable.defaults.extend.index_url,

                escape: false,

                pk: 'id',

                sortName: 'create_time',

                pagination: true,

                pageSize: 10,

                commonSearch: false,

                queryParams: function queryParams(params) {

                    var searchForm = $("form[role=form]");
                    //  console.log(searchForm);
                    if (searchForm.length) {

                        var searchFields = searchForm.serializeArray();

                        for (var i = 0; i < searchFields.length; i++) {

                            if (searchFields[i]['value']) {

                                params[searchFields[i]['name']] = searchFields[i]['value'];

                            }

                        }

                    }

                    //params['docid'] = 6;

                    return params;

                },

                queryParamsType: "limit",

                columns: [

                    [

                        { checkbox: true },

                        { field: 'id', title: __('Id') },



                        {

                            field: 'project',

                            title: __('Project'),

                            formatter: function(project) {

                                if (project) {

                                    return project.name;

                                }

                                return '';

                            }

                        },

                        {

                            field: 'document',

                            title: __('Document'),

                            formatter: function(document) {

                                if (document) {

                                    return document.name;

                                }

                                return '';

                            }

                        },

                        {

                            field: 'pay',

                            title: __('Pay'),

                            formatter: function(pay) {

                                if (pay) {

                                    return pay.name;

                                }

                                return '';

                            }

                        },

                        { field: 'amount_total', title: __('AmountTotal') + '（&yen;）', operate: false, formatter: Table.api.formatter.amount },

                        { field: 'amount_paid', title: __('AmountPaid') + '（&yen;）', operate: false, formatter: Table.api.formatter.amount },

                        {

                            field: 'type',

                            title: __('Type'),

                            formatter: function(value) {

                                var statuses = [__('RentNew'), __('RentRenew'), __('RentSublet')];

                                return statuses[value]

                            }

                        },

                        { field: 'remark', title: __('Remark'), operate: false },

                        { field: 'payment_date', title: __('PaymentDate') },

                        { field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate }

                    ]

                ]

            });



            // 为表格绑定事件

            Table.api.bindevent(table);

            Controller.handleCommunityState(true);

            $("#community_code").change();

            Controller.api.bindevent();

            $("#common_search").bind("click", function() {

                table.bootstrapTable('refresh', {

                    url: $.fn.bootstrapTable.defaults.extend.index_url,

                    pageNumber: 1

                });

            });

        },

        detail: function() {

            Controller.api.bindevent();

        },

        add: function() {

            Controller.handleCommunityState();

            $("#community_code").change();

            Controller.api.bindevent();





        },

        docitems: function() {

            // 初始化表格参数配置

            Table.api.init({

                extend: {

                    index_url: 'expenses/index',

                    add_url: 'expenses/index/add' + location.search,

                    edit_url: 'expenses/index/edit',

                    del_url: 'expenses/index/del',

                    table: 'expenses',

                }

            });



            var table = $("#table");

            // 初始化表格

            table.bootstrapTable({

                url: $.fn.bootstrapTable.defaults.extend.index_url,

                escape: false,

                pk: 'id',

                sortName: 'create_time',

                pagination: false,

                pageSize: 10,
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,

                commonSearch: false,

                queryParams: function queryParams(params) {

                    var params;
                    params['docid'] = $('#docid').val();
                    return params;
                },

                queryParamsType: "limit",

                columns: [

                    [



                        // { field: 'id', title: __('Id') },

                        {

                            field: 'house',

                            title: __('House'),

                            formatter: function(house) {

                                if (house) {

                                    return house.name;

                                }

                                return '';

                            }

                        },



                        { field: 'amount_total', title: __('AmountTotal') + '（&yen;）', operate: false, formatter: Table.api.formatter.amount },

                        { field: 'amount_paid', title: __('AmountPaid') + '（&yen;）', operate: false, formatter: Table.api.formatter.amount },

                        { field: 'remark', title: __('Remark'), operate: false },

                        { field: 'payment_date', title: __('PaymentDate') },

                        {

                            field: 'operate',

                            title: __('Operate'),

                            table: table,

                            events: Table.api.events.operate,

                            formatter: function(value, row, index) {

                                this.buttons = [{

                                    name: 'fix',

                                    title: '修复付款项',

                                    icon: 'fa fa-wrench',

                                    classname: 'btn btn-success btn-xs btn-fix'

                                }];
                                //return Table.api.buttonlink(this, this.buttons, value, row, index, 'operate');


                                return Table.api.formatter.operate.call(this, value, row, index);

                            },
                        }


                    ]

                ]

            });


            // 为表格绑定事件

            Table.api.bindevent(table);

            table.on('click', '.btn-fix', function(e) {

                e.stopPropagation();
                var data = table.bootstrapTable('getData');
                var index = $(this).closest('tr').data('index');
                var community_code = data[index]['community_code'];
                var docid = data[index]['docid'];
                var companyid = data[index]['companyid'];
                var pay_code = data[index]['pay_code'];
                $('#community_code').val(community_code);
                $('#docid').val(docid);
                $('#companyid').val(companyid);
                $('#pay_code').val(pay_code);


                var freenums = data[index]['freenums'];
                var chargearea = data[index]['chargearea'];
                var firstunitprice = data[index]['amount_total'] / chargearea;
                $('#freenums').val(freenums);
                $('#chargearea').val(chargearea);
                $('#firstunitprice').val(firstunitprice);

                var project_code = data[index]['project_code'];
                var house_code = data[index]['house_code'];
                $('#project_code').selectpicker('val', project_code);
                $('#house_code').selectpicker('val', house_code);
                addplan();
                $('#isfix').val(1);
            })

            Controller.handleCommunityState();

            $("#community_code").change();

            Controller.api.bindevent();

        },

        edit: function() {

            Controller.handleCommunityState();

            $("#community_code").change();

            Controller.api.bindevent();

        },

        api: {

            bindevent: function() {

                Form.api.bindevent($("form[role=form]"));

            }

        },

        handleCommunityState: function(showAll) {

            var house_id = $("#house_id").val();

            var project_id = $("#project_id").val();

            $("#community_code").bind("change", function() {

                var community_code = $(this).val();

                $.ajax({

                    type: "POST",

                    url: 'expenses/index/get_project_by_cm_code',

                    async: true,

                    cache: false,

                    dataType: "json",

                    data: { community_code: community_code },

                    success: function(data) {

                        var project = data.project;

                        var house = data.house;



                        var projectHtml = showAll ? '<option value="">全部</option>' : '';

                        $.each(project, function(index, item) {

                            projectHtml += '<option value="' + item.code + '">' + item.name + '</option>';

                        });

                        if (projectHtml == '') {

                            projectHtml = '<option value="">没有任何选中项</option>';

                        }

                        $("#project_code").html(projectHtml);

                        if (project_id) {

                            $("#project_code").val(project_id);

                        }



                        var houseHtml = showAll ? '<option value="">全部</option>' : '';

                        $.each(house, function(index, item) {

                            houseHtml += '<option value="' + item.code + '">' + item.name + '</option>';

                        });

                        if (houseHtml == '') {

                            houseHtml = '<option value="">没有任何选中项</option>';

                        }

                        $("#house_code").html(houseHtml);

                        if (house_id) {

                            $("#house_code").val(house_id);

                        }

                        setTimeout(function() {

                            $("#project_code").selectpicker({

                                showTick: true,

                                liveSearch: true

                            });

                            $("#project_code").selectpicker("refresh");

                            $("#house_code").selectpicker({

                                showTick: true,

                                liveSearch: true

                            });

                            $("#house_code").selectpicker("refresh");





                        }, 200)

                    }

                });

            });

        }

    };

    return Controller;

});





var submitData = function(i) {

    var amount_total_control = $("input[name='amount_total']");

    var payment_date_control = $("input[name='payment_date']");

    var amount_unitprice = $("input[name='amount_unitprice']");
    var remark = $("input[name='remark']");

    var isfix = $('#isfix').val();
    var param = $('form').serializeArray();
    console.log(param);
    console.log(i);
    //如果是修复的，先清零
    if (i == 0 && isfix == 1) {

        $.post('expenses/index/clear', param, function(json) {
            $('#isfix').val(0);
            submitData(0);
        }, 'json');
        return;
    }

    if (i >= amount_total_control.length) {
        // console.log(amount_total_control.length);
        //Fast.api.close();

        //parent.$("a.btn-refresh").trigger("click");

        // var totalmoney = $('#doc_amount_total').val();
        //var docparam = [{ 'name': 'ids', 'value': $('#docid').val() }, { 'name': 'totalamount', 'value': totalmoney }];
        var docparam = { id: $('#docid').val() };
        $.post('document/index/sumamount', docparam, function(json) {
            // window.location.href = window.location.href;
            //layer.msg('新增了合同收款项');
            Fast.api.close();
        })

        return;

    }

    // var param = $('form').serializeArray();

    param.push({ 'name': 'row[amount_total]', 'value': amount_total_control.eq(i).val() });

    param.push({ 'name': 'row[payment_date]', 'value': payment_date_control.eq(i).val() });

    param.push({ 'name': 'row[unitprice]', 'value': amount_unitprice.eq(i).val() });
    param.push({ 'name': 'row[remark]', 'value': remark.eq(i).val() });

    $.post('expenses/index/add', param, function(json) {
        //console.log(json);
        i++;
        submitData(i);
    }, 'json')



}



var addplan = function() {

    var times = Math.round($('#times').val());

    if (times < 0) {
        layer.msg('起租或止租日期错误');
        return;
    }
    //  console.log(times);

    var totalmoney = 0;
    var amount_total = 0;
    var unitprice = $('#firstunitprice').val();

    var chargearea = $('#chargearea').val();

    var intervalYears = $('#intervalYear').val();

    var rate = $('#rate').val();

    var bgindatestr = $('#bgindate').val();
    var enddatestr = $('#endate').val();
    var freenums = $('#freenums').val();



    if (times == null) {

        return;

    }



    if (!(times | 0)) {

        layer.msg('分期次数应为整数');

        return;

    }



    if (isNaN(parseFloat(chargearea)) || parseFloat(chargearea) <= 0) {

        layer.msg('计租面积不能为空');

        return;

    }



    if (isNaN(parseFloat(unitprice))) {

        layer.msg('请填写单价');

        return;

    }



    if (isNaN(parseFloat(freenums))) {

        layer.msg('赠送数量不能为空，无请真写0');

        return;

    }


    if (!isNaN(parseFloat(intervalYears)) && isNaN(parseFloat(rate))) {

        layer.msg('增长率不能为空');

        return;

    }



    if (isNaN(parseFloat(intervalYears))) {

        intervalYears = 0;

    }





    if (!isNaN(bgindatestr) || isNaN(Date.parse(bgindatestr))) {

        layer.msg('计费开始日期格式错误');

        return;

    }

    rate = rate / 100;
    var freedays = parseFloat(freenums);
    times = Math.ceil((times - freedays) / 365).toFixed(1);

    //var unitmoney = totalmoney / times;
    //time = Math.floor(times / 365);

    //  var bgdate = new Date(bgindatestr);
    //  var enddate = new Date(enddatestr);
    var yearunitprice = parseFloat(unitprice); //年租金
    var realunitprice = parseFloat(unitprice);
    var t = $("#unittype").val();
    if (t == 1) {
        realunitprice = parseFloat(realunitprice / 365);
        realunitprice = realunitprice.toFixed(2);

    } else {
        yearunitprice = yearunitprice * 365;
    }

    $('#mypayplan').show();
    $('#payplan').nextAll().remove();
    var isCycle = 1; //增长周期计数
    // realunitprice = realunitprice * chargearea;

    var ms = monDiff(enddatestr, bgindatestr); //间隔月数

    ms = ms / 12;

    var bgdate = new Date(bgindatestr);
    var enddate = new Date(enddatestr);
    var yearstartdate = new Date(bgindatestr);
    var yearenddate = new Date(bgindatestr);

    // for (var i = 0; i < times; i++) {
    //     var html = $('#payplan').clone(true).attr('id', 'payplan' + i);
    //     html.find('.btn-danger').remove();
    //     $('#mypayplan').append(html);
    // }

    var i = 0;
    while (true) {

        //  yearstartdate.setMonth(yearstartdate.getMonth(), yearstartdate.getDate()); //本年开始计租时间
        if (i === 0)
            yearstartdate.setDate(yearstartdate.getDate() + freedays);
        else
            yearstartdate.setDate(yearstartdate.getDate() + 1);

        console.log('yearstartdate', yearstartdate);
        //  yearenddate.setMonth(yearstartdate.getMonth() + 12, yearstartdate.getDate() - 1); //本年截止计租时间
        yearenddate.setFullYear(yearstartdate.getFullYear() + 1, yearstartdate.getMonth(), yearstartdate.getDate() - 1); //本年截止计租时间

        console.log('yearenddate', yearenddate);
        //yearenddate.setDate(yearstartdate.getDate() - 1);
        var endsplitdays = getDaysBetween(yearstartdate, enddate); //最后本年开始天数和真实合同截止的天数数量
        console.log(endsplitdays);

        if (endsplitdays <= 0) //没有租期了，循环完成了
            break;

        //是否满年
        // if (endsplitdays < 395) {
        //     yearenddate = new Date(enddate);
        // }

        var ratedate = new Date(bgdate); //新老计费日期分界点
        ratedate.setMonth(ratedate.getMonth() + (isCycle * intervalYears * 12), ratedate.getDate());
        var amount_remark; //计费说明

        if (yearenddate.getTime() > enddate.getTime()) {
            yearenddate = new Date(enddate);



            var yearDays = getDaysBetween(yearstartdate, yearenddate); //本年天数
            amount_total = realunitprice * chargearea * yearDays;

            //amount_remark = yearDays + "天*" + realunitprice.toFixed(0) + '元';
        } else {
            amount_total = yearunitprice * chargearea;
        }

        if (intervalYears > 0 && yearenddate.getTime() >= ratedate.getTime() && yearstartdate.getTime() < ratedate.getTime()) //如果到了增真的那年
        {
            var yearDays_1 = getDaysBetween(yearstartdate.toLocaleDateString(), ratedate.toLocaleDateString()); //涨价前的天数
            var yearDays_2 = getDaysBetween(ratedate.toLocaleDateString(), yearenddate.toLocaleDateString()); //涨价后的天数
            var amount_total_1 = realunitprice * chargearea * yearDays_1;

            //amount_remark = yearDays_1 + "天*" + realunitprice.toFixed(0) + '元';
            // realunitprice = parseFloat((realunitprice) + (isCycle * rate * realunitprice));
            yearunitprice = parseFloat((yearunitprice) + (isCycle * rate * yearunitprice)); //新的年租金
            realunitprice = yearunitprice / 365;
            var amount_total_2 = realunitprice * chargearea * yearDays_2;
            amount_total = amount_total_1 + amount_total_2;

            // amount_remark += " ; " + yearDays_2 + "天*" + realunitprice.toFixed(0) + '元';
            isCycle++;
        }


        // var legen = yearstartdate.toLocaleDateString() + '--' + yearenddate.toLocaleDateString() + "; " + amount_remark;
        var legen = yearstartdate.toLocaleDateString() + '--' + yearenddate.toLocaleDateString();
        var paydate = new Date(yearstartdate); //付款日期
        paydate.setMonth(paydate.getMonth() - 1, paydate.getDate());
        // if (paydate.getTime() < bgdate.getTime())
        //     paydate = new Date(bgdate);


        amount_total = amount_total.toFixed(0);

        if (i > 0) {
            var html = $('#payplan').clone(true).attr('id', 'payplan' + i);
            html.find('.btn-danger').remove();
            $('#mypayplan').append(html);
        }
        $("#mypayplan >.payplan").eq(i).find("span[name='remark']").text(legen);
        $("#mypayplan >.payplan").eq(i).find("input[name='amount_total']").val(amount_total);
        $("#mypayplan >.payplan").eq(i).find("input[name='payment_date']").val(paydate.toLocaleDateString());
        $("#mypayplan >.payplan").eq(i).find("input[name='remark']").val(legen);
        $("#mypayplan >.payplan").eq(i).find("input[name='amount_unitprice']").val(unitprice);
        totalmoney = parseFloat(totalmoney) + parseFloat(amount_total);

        yearstartdate = new Date(yearenddate);

        i++;
    }



    $('#doc_amount_total').val(totalmoney);

    // $('#times').val(times);

    $('.datetimepicker').datetimepicker();



}

var monDiff = function(date1, date2) {
    // 拆分年月日
    date1 = date1.split('-');
    // 得到月数
    date1 = parseInt(date1[0]) * 12 + parseInt(date1[1].replace(/\b(0+)/gi, "")) + parseInt(date1[2].replace(/\b(0+)/gi, "")) / 30;
    // 拆分年月日
    date2 = date2.split('-');

    // 得到月数
    date2 = parseInt(date2[0]) * 12 + parseInt(date2[1].replace(/\b(0+)/gi, "")) + parseInt(date2[2].replace(/\b(0+)/gi, "")) / 30;

    var m = Math.round(date1 - date2);
    return m;
}

function getDaysBetween(dateString1, dateString2) {
    var startDate = Date.parse(dateString1);
    var endDate = Date.parse(dateString2);
    var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
    // alert(days);
    return days;
}